package com.cskaoyan.mall.product.runner;

import com.cskaoyan.mall.common.constant.RedisConst;
import com.cskaoyan.mall.product.service.SkuService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * @Author Pudding
 * @Date 2024/7/6 14:31
 */
@Slf4j
@Component
public class BloomFilterRunner implements CommandLineRunner {

    @Autowired
    RedissonClient redissonClient;
    @Autowired
    SkuService skuService;

    @Override
    public void run(String... args) throws Exception {

        RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(RedisConst.SKU_BLOOM_FILTER);

        long expectedInsertions = 1000000;  //期望存储的元素的数量
        double falseProbability = 0.01d;    //误判率

        //1. 初始化布隆过滤器
        boolean result = bloomFilter.tryInit(expectedInsertions, falseProbability);

        //2. 方式一：在每次服务启动的时候，不仅仅只初始化布隆过滤器，还可以把数据库中所有已经上架的商品都查询出来，存入布隆过滤器
        skuService.initBloomFilter();


        if (result) {
            log.info("布隆过滤器初始化成功，初始化布隆过滤器的结果：{}", result);
        } else {
            log.info("布隆过滤器初始化失败");
        }
    }
}
